<?php
namespace app\__MODULE__\controller;
use think\facade\Db;
use app\__MODULE__\model\{Question as QuestionModel,Option,Answer};

class Question extends Base{
    

    /**
     * 首页
     */
    public function index(){
        if(IS_POST) {
            $search  = request()->param();
            $where = [];
            if(isset($search['title'])&&$search['title'] !=''){
                $where[] = ['title','like',"%{$search['title']}%"];
            } 
            $db   = QuestionModel::where($where)->order('id desc');
            $list = $db->limit(paginator())->select();
            
            admin_response(0, 'success', $list, $db->count());
        }

        return $this->render_table([
           "page"=>true,
            "toolbar" => [
                table_button('admin/Question/add',"添加","frame"),
                table_button('admin/Question/down_temp',"下载模板","url"),
                table_button('admin/Question/import',"导入","upload",'.csv')
            ],
            "toolbar_row" => [ 
                    table_button('admin/Question/edit',"编辑","frame"),
                    table_button('admin/Question/del',"删除","confirm")
                    ],
            "cols" => [ 
                     ["type"=>"checkbox"],
                    ["field"=>"id", "title"=>"编号","align"=>"center"],
                    ["field"=>"title", "title"=>"标题","align"=>"center"],
                    ["field"=>"right_answer", "title"=>"正确答案","align"=>"center"],

            ],
            "where"=>[
                'title'  => ['type'=>'input', 'title'=>'关键字','placeholder'=>'题目名称搜索'],
            ]

            ],false);

    }

        /**
     * 批量导入
     * @return void
     * @author Sam
     * date 2021-07-02
     */
    public function import(){
        set_time_limit(0);
        if(empty($_FILES['file'])) json_response(0, '请选择文件');
        $data = big_csv_to_array($_FILES['file']['tmp_name']);
        $num = 0;
        foreach ($data as $value) {
            if(!empty($value[0])) {
                Db::startTrans();
                try {
                    $question =  QuestionModel::create([
                         'title' => trim((string)$value[0]),
                         'remark' => trim((string)$value[7]),
                         'right_answer' => trim((string)$value[6])
                     ]);
                     $insert_data = ['A'=>$value[1],'B'=>$value[2],'C'=>$value[3],'D'=>$value[4],'E'=>$value[5]];
                     foreach($insert_data as $k=>$v){
                         if(trim($v) != '' && $v){
                              $option =  Option::create([
                                 'question_id' => $question->id,
                                 'option_name' => $v,
                                 'option_number'  => $k 
                             ]);
                         }
                         if($k == trim((string)$value[6])){
                             $question->answer_id = $option->id;
                             $question->save();
                         }
                     }
                     $num += 1;
                    Db::commit();
                 } catch (\Exception $e) {
                    Db::rollback();
                    $num = 0;
                    json_response(0,$e->getMessage());
                 }
               
            }
        }
        json_response(1,"成功导入{$num}条数据");
    }

    /**
     * 答题记录
     *
     * @return void
     * @Description
     * @example
     * @author Sam
     * @since 
     */
    public function record(){
        if(IS_POST) {
            $search  = request()->param();
            $where = [];
            if(isset($search['question']) && $search['question'] !=''){
                $ids = Question::where('title','like',"%{$search['question']}%")->column('id');
                if($ids && is_array($ids)){
                    $where[] = ['question_id','in',$ids];
                } 
            }
            if(isset($search['user']) && $search['user'] !=''){
                $ids = User::where('mobile|name','like',"%{$search['user']}%")->column('id');
                if($ids && is_array($ids)){
                    $where[] = ['uid','in',$ids];
                } 
            }
            if(isset($search['is_right']) && $search['is_right'] !=''){
                $where[] = ['is_right','=',$search['is_right']];
            }
            $db   = Answer::with(['user','question'])->where($where)->order('id desc');
            $list = $db->limit(paginator())->select();
            foreach ($list as $key => $value) {
                if($value['is_right']==1){
                   $value['answer'] =  "<span style='color:blue'>正确</span>";
                }else{
                    $value['answer'] =  "<span style='color:red'>错误</span>";
                }
            }
            admin_response(0, 'success', $list, $db->count());
        }

        if(IS_EXCEL) {
            $db = Answer::with(['user','question'])->where($where)->order('id asc');
            big_array_to_csv($db, '答题记录', [ 
                'id'                => '编号',
                'user_name'         => '姓名',
                'mobile'            => '手机号',
                'question'          => '题目',
                'answer_number'     => '答案',
                'is_right'          => ['是否正确',function($row){
                    return $row['is_right'] == 1 ?'正确':'错误';
                }],
                'answer_time'       => '答题时间',
            ]);
        }

        return $this->render_table([
           "page"=>true,
           "export" => true,
            "cols" => [ 
                    ["field"=>"id", "title"=>"编号","align"=>"center"],
                    ["field"=>"user_name", "title"=>"姓名","align"=>"center"],
                    ["field"=>"question", "title"=>"问题","align"=>"center"],
                    ["field"=>"answer_number", "title"=>"答案","align"=>"center"],
                    ["field"=>"answer", "title"=>"是否正确","align"=>"center"],
            ],
            "where"=>[
                'user'  => ['type'=>'input', 'title'=>'用户','placeholder'=>'姓名，手机号搜索'],
                'question'  => ['type'=>'input', 'title'=>'题目','placeholder'=>'题目名称搜索'],
                'is_right'  => ['type'=>'select', 'title'=>'是否正确','option'=>[
                    ['title'=>'正确','value'=>1],
                    ['title'=>'错误','value'=>0]
                ]],
            ]

            ],false);

    }

    /**
     * 下载模板
     *
     * @return void
     * @Description
     * @example
     * @author Sam
     * @since 
     */
    public function down_temp(){
      header("Location:https://game.vrupup.com/resources/sam_base/answer.csv");
      exit();
    }



        /**
     * 添加
     * @return void
     * @author 
     * date 
     */
    public function add(){
        if(request()->isPost()) {
           $postData  = request()->post();
            $option = [];
            if(count(array_filter($postData['option_name'])) != count(array_filter($postData['option_number']))){
                json_response(0,'请完善选项');
            }
            if((!count($postData['option_number']) ||!count($postData['option_name']))){
                json_response(0,'请至少添加一个选项');
            }
            foreach ($postData['option_number'] as $key => $value) {
                if(!in_array($value,['A','B','C','D','E','F','G','H'])){
                    json_response(0,'选项编号格式仅限A,B,C等,勿添加空格');
                }
                $option[$value] = $postData['option_name'][$key];
            }
            $postData['option'] = $option;
            if(!in_array($postData['right_answer'],$postData['option_number'])){
                json_response(0,'该答案在选项中不存在');
            }
            if(QuestionModel::where('title',$postData['title'])->count()){
                json_response(0,'该题目已存在');
            }
            Db::startTrans();
            try {
               $question =  QuestionModel::create([
                    'title'        => $postData['title'],
                    'remark'       => $postData['remark'],
                    'right_answer' => $postData['right_answer'],
                    'pic'          => $postData['pic'] ?? ''
                ]);
                if($postData['option']){
                    foreach ($postData['option'] as $key => $value) {
                       $Option =  Option::create([
                            'question_id' => $question->id,
                            'option_name' => $value,
                            'option_number' => $key
                        ]);
                        if($key == $postData['right_answer']){
                            $question->answer_id = $Option->id;
                            $question->save();
                        }
                    }
                }
               Db::commit();
            } catch (\Exception $e) {
               Db::rollback();
               json_response(0,$e->getMessage());
            }
            json_response(1,'添加成功');
        }else{
            return $this->fetch();
        }
    }

        /**
     * 删除选项
     * @return void
     * @author Sam
     * date 2021-02-26
     */
    public function del_option(){
        if(request()->isPost()){
            $id       = request()->post('id/d');
            $question = request()->post('question/d');
            if($option = Option::where(['question_id'=>$question,'id'=>$id])->find()){
                if($option->delete()){
                    json_response(1,'删除成功');
                }else{
                    json_response(0,'删除失败');
                }
            }else{
                json_response(0,'无此选项记录');
            }
        }else{
            json_response(0,'非法请求');
        }
    }

    /**
     * 编辑
     * @return void
     * @author 
     * date 
     */
    public function edit(){
           $id = \param_check('id');
          if(request()->isPost()){
            $postData  = request()->post();
            $option = [];
            if(count(array_filter($postData['option_name'])) != count(array_filter($postData['option_number']))){
                json_response(0,'请完善选项');
            }
            if((!count($postData['option_number']) ||!count($postData['option_name']))){
                json_response(0,'请至少添加一个选项');
            }
            foreach ($postData['option_number'] as $key => $value) {
                if(!in_array($value,['A','B','C','D','E','F','G','H'])){
                    json_response(0,'选项编号格式仅限A,B,C等');
                }
                $option[$value] = $postData['option_name'][$key];
            }
            $postData['option'] = $option;
            if(!in_array($postData['right_answer'],$postData['option_number'])){
                json_response(0,'该答案在选项中不存在');
            }
            Db::startTrans();
            try {
                if(!$question = QuestionModel::get($id)) json_response(0,'无此题目');
                $question->save($postData);
                if($postData['option']){
                    foreach ($postData['option'] as $key => $value) {
                        if($option = Option::where('question_id',$id)->where('option_number',$key)->find()){
                            $option->option_name = $value;
                            $option->option_number = $key;
                            $option->save();
                        }else{
                            Option::create([
                                'question_id' => $question->id,
                                'option_name' => $value,
                                'option_number' => $key
                            ]);
                        }
                      
                    }
                }
               Db::commit();
            } catch (\Exception $e) {
               Db::rollback();
               json_response(0,$e->getMessage());
            }
            return json_response(1,'编辑成功');
        }else{
             if(!$id) json_response('缺少ID');
             if(!$info = QuestionModel::get($id)) json_response(0,'无此信息');
             $this->assign('info',$info);
             return $this->fetch();
        }
    }





        /**
     * 删除
     * @return void
     * @author Sam
     * date 2021-07-01
     */
    public function del(){
        $id = param_check('id');
        if(!$QuestionModel = QuestionModel::get($id)) json_response(0,'不存在');
        if($QuestionModel->delete()) json_response(1,'操作成功');
        json_response(0,'操作失败');
    }

}